package com.hutu.kboshi.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hutu.kboshi.common.ErrorCode;
import com.hutu.kboshi.common.constant.CommonConstant;
import com.hutu.kboshi.common.exception.ThrowUtils;
import com.hutu.kboshi.dao.QuestionBankDao;
import com.hutu.kboshi.dao.QuestionBankQuestionDao;
import com.hutu.kboshi.dao.QuestionDao;
import com.hutu.kboshi.dao.UserDao;
import com.hutu.kboshi.pojo.dto.questionbank.QuestionBankQueryRequest;
import com.hutu.kboshi.pojo.entity.QuestionBank;
import com.hutu.kboshi.pojo.entity.QuestionBankQuestion;
import com.hutu.kboshi.pojo.entity.User;
import com.hutu.kboshi.pojo.vo.QuestionBankVO;
import com.hutu.kboshi.service.QuestionBankService;
import com.hutu.kboshi.utils.SqlUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 20272
* @description 针对表【question_bank(题库)】的数据库操作Service实现
* @createDate 2024-09-24 22:41:22
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class QuestionBankServiceImpl implements QuestionBankService {


    private final QuestionBankDao questionBankDao;

    private final QuestionBankQuestionDao questionBankQuestionDao;

    private final QuestionDao questionDao;

    private final UserDao userDao;
    /**
     * 校验数据
     *
     * @param questionBank
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validQuestionBank(QuestionBank questionBank, boolean add) {
        ThrowUtils.throwIf(questionBank == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        String title = questionBank.getTitle();
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (StringUtils.isNotBlank(title)) {
            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(QuestionBank questionBank) {
        boolean save = questionBankDao.save(questionBank);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public QuestionBank getQuestionBankById(long id) {
        return questionBankDao.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeQuestionBankById(long id) {
        questionBankQuestionDao.removeQuestionBankQuestionByBankId(id);
        questionBankDao.removeById(id);
    }

    @Override
    public boolean updateById(QuestionBank questionBank) {
        return questionBankDao.updateById(questionBank);
    }

    @Override
    public Page<QuestionBank> pages(QuestionBankQueryRequest questionBankQueryRequest) {
        long current = questionBankQueryRequest.getCurrent();
        long size = questionBankQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 200, ErrorCode.PARAMS_ERROR);
        // 根据tag来筛选出题目
        List<Long> questionIds = questionDao.findQuestionIdsByTag(questionBankQueryRequest.getTag());
        // 根据题目的id来筛选出题库
        Page<QuestionBankQuestion> page = new Page<>(current, size);
        page = questionBankQuestionDao.findQuestionBankIdsByQuestionIds(page,questionIds);
        List<QuestionBankQuestion> records = page.getRecords();
        Set<Long> questionBankIds = new HashSet<>();
        if (CollUtil.isNotEmpty(records)){
            questionBankIds = records.stream().map(QuestionBankQuestion::getQuestionBankId).collect(Collectors.toSet());
        }
        Page<QuestionBank> bankPage = new Page<>(current, size);
        return questionBankDao.findQuestionBankPageByIds(bankPage,questionBankIds);
    }

    @Override
    public Page<QuestionBank> pagess(QuestionBankQueryRequest questionBankQueryRequest) {
        long current = questionBankQueryRequest.getCurrent();
        long size = questionBankQueryRequest.getPageSize();
        Page<QuestionBank> page = new Page<>(current, size);
        return questionBankDao.page(page,getQueryWrapper(questionBankQueryRequest));
    }
    public QueryWrapper<QuestionBank> getQueryWrapper(QuestionBankQueryRequest questionBankQueryRequest) {
        QueryWrapper<QuestionBank> queryWrapper = new QueryWrapper<>();
        if (questionBankQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = questionBankQueryRequest.getId();
        String title = questionBankQueryRequest.getTitle();
        String sortField = questionBankQueryRequest.getSortField();
        String sortOrder = questionBankQueryRequest.getSortOrder();
        String description = questionBankQueryRequest.getDescription();


        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    @Transactional
    public Boolean checkProcessAndUpdate(QuestionBank questionBank) {
        return questionBankDao.updateById(questionBank);
    }

    @Override
    public Page<QuestionBankVO> getQuestionBankVOPage(Page<QuestionBank> questionBankPage, HttpServletRequest request) {
        List<QuestionBank> questionBankList = questionBankPage.getRecords();
        Page<QuestionBankVO> questionBankVOPage = new Page<>(questionBankPage.getCurrent(), questionBankPage.getSize(), questionBankPage.getTotal());
        if (CollUtil.isEmpty(questionBankList)) {
            return questionBankVOPage;
        }
        // 对象列表 => 封装对象列表
        List<QuestionBankVO> questionBankVOList = questionBankList.stream().map(questionBank -> {
            return QuestionBankVO.objToVo(questionBank);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionBankList.stream().map(QuestionBank::getCreateBy).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userDao.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        questionBankVOList.forEach(questionBankVO -> {
            Long userId = questionBankVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
//            questionBankVO.setUser(userService.getUserVO(user));
        });
        // endregion

        questionBankVOPage.setRecords(questionBankVOList);
        return questionBankVOPage;
    }

}




